package com.zhxin.nettylab.nio.chapter2;

import java.io.*;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @ClassName BufferTest
 * @Description //BufferTest FileChannel文件通道 demo
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/3 0003 下午 2:43
 **/
public class ChannelTest {

    public static void main(String[] args){
        File bt = new File("E:/project/nettylab/src/main/resources/buffer.txt");

        //当try语句块运行结束时，FileInputStream 会被自动关闭
        // 这是因为FileInputStream 实现了java中的java.lang.AutoCloseable接口
        // 所有实现了这个接口的类都可以在try-with-resources结构中使用
        // 以FileInputStream、FileOutputStream 文件输入流和文件输出流来创建FileChannel

        try(FileChannel inCnl = new FileInputStream(bt).getChannel();
            FileChannel outCnl = new FileOutputStream("E:/project/nettylab/src/main/resources/buffer1.txt").getChannel()){
            MappedByteBuffer bf = inCnl.map(FileChannel.MapMode.READ_ONLY,0,bt.length()); //从Channel获取数据
            Charset crt = Charset.forName("UTF-8");
            outCnl.write(bf); //向Channel写数据
            bf.clear();
            CharsetDecoder cd = crt.newDecoder();

            //decode 把ByteBuffer 转 CharBuffer
            CharBuffer cb = cd.decode(bf);
            System.out.println(cb);


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
